/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved.
 */

package com.huawei.idea.share;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.huawei.idea.ideasharesdk.object.CallStatus;
import com.huawei.idea.ideasharesdk.object.RemoteServiceStatus;
import com.huawei.idea.ideasharesdk.object.ShareStatus;
import com.huawei.idea.ideasharesdk.sdk.Callback;
import com.huawei.idea.ideasharesdk.sdk.IShareServiceController;
import com.huawei.idea.ideasharesdk.sdk.ShareServiceController;
import com.huawei.idea.ideasharesdk.utils.Constant;
import com.huawei.idea.ideasharesdk.utils.LogUtil;
import com.huawei.idea.share.observer.DeviceStatusObserver;

import java.util.Arrays;

/**
 * 会控页面
 *
 * @author w00415409
 * @since 2021/2/10
 */
public class RemoteActivity extends Activity implements DeviceStatusObserver {
    private static final int ERROR_SIGNAL = 0;

    private static final int INIT_COMPONENT_SIGNAL = 1;

    private static final int SET_MIC_MUTE_SIGNAL = 2;

    private static final int SET_CAMERA_MUTE_SIGNAL = 3;

    private static final int SET_SPEAKER_MUTE_SIGNAL = 4;

    private static final int PROJECTION_SUCCESS_SIGNAL = 5;

    private static final int PROJECTION_STOP_SIGNAL = 6;

    private static final int LEAVE_MEETING_SIGNAL = 7;

    private static final int SDK_VERSION_SIGNAL = 8;

    private final String TAG = RemoteActivity.class.getSimpleName();

    private TextView deviceName;

    private Button micMuteBtn;

    private Button cameraMuteBtn;

    private ImageView speakerImg;

    private SeekBar volumeBar;

    private Button leaveMeetingBtn;

    private CheckBox endMeetingCheckbox;

    private Button projectionBtn;

    private Button projectionStopBtn;

    private TextView versionTxt;

    private Switch audioSwitch;

    private IShareServiceController shareServiceController;

    private boolean isMicMute;

    private boolean isCameraMute;

    private boolean isSpeakerMute;

    private boolean isChairman;

    private boolean audioEnabled = false;

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            final int signal = msg.what;
            switch (signal) {
                case ERROR_SIGNAL:
                    int retCode = msg.arg1;
                    LogUtil.debug(TAG, "error code: " + retCode);
                    ShowErrorUtil.showErrorMsg(getApplicationContext(), retCode);
                    break;
                case INIT_COMPONENT_SIGNAL:
                    RemoteServiceStatus remoteServiceStatus = (RemoteServiceStatus) msg.obj;
                    LogUtil.debug(TAG, "INIT_COMPONENT_SIGNAL: " + remoteServiceStatus);
                    setComponentStatus(remoteServiceStatus);
                    break;
                case SET_MIC_MUTE_SIGNAL:
                    LogUtil.debug(TAG, "SET_MIC_MUTE_SIGNAL: ");
                    micMuteBtn.setText(isMicMute ? "Mic Mute" : "Cancel Mute");
                    isMicMute = !isMicMute;
                    break;
                case SET_CAMERA_MUTE_SIGNAL:
                    LogUtil.debug(TAG, "SET_CAMERA_MUTE_SIGNAL: ");
                    cameraMuteBtn.setText(isCameraMute ? "Camera Mute" : "Cancel Mute");
                    isCameraMute = !isCameraMute;
                    break;
                case SET_SPEAKER_MUTE_SIGNAL:
                    LogUtil.debug(TAG, "SET_SPEAKER_MUTE_SIGNAL: ");
                    speakerImg.setImageResource(isSpeakerMute ? R.drawable.ic_speaker_unmute : R.drawable.ic_speaker_mute);
                    isSpeakerMute = !isSpeakerMute;
                    break;
                case PROJECTION_SUCCESS_SIGNAL:
                    LogUtil.debug(TAG, "PROJECTION_SUCCESS_SIGNAL: ");
                    projectionBtn.setVisibility(View.GONE);
                    projectionStopBtn.setVisibility(View.VISIBLE);
                    break;
                case PROJECTION_STOP_SIGNAL:
                    LogUtil.debug(TAG, "PROJECTION_STOP_SIGNAL: ");
                    projectionBtn.setVisibility(View.VISIBLE);
                    projectionStopBtn.setVisibility(View.GONE);
                    break;
                case LEAVE_MEETING_SIGNAL:
                    LogUtil.debug(TAG, "LEAVE_MEETING_SIGNAL: ");
                    leaveMeetingBtn.setVisibility(View.GONE);
                    endMeetingCheckbox.setVisibility(View.GONE);
                    break;
                case SDK_VERSION_SIGNAL:
                    String version = (String) msg.obj;
                    LogUtil.debug(TAG, "SDK_VERSION_SIGNAL version: " + version);
                    versionTxt.setText(version);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote_layout);
        DemoApp.getInstance().attachMeetingObserver(this);
        shareServiceController = ShareServiceController.getInstance();
        deviceName = findViewById(R.id.id_txt_deviceName);
        String intentDeviceName = getIntent().getStringExtra("deviceName");
        if (intentDeviceName != null) {
            deviceName.setText(intentDeviceName);
        }
        audioSwitch = findViewById(R.id.id_switch_audioEnable);
        micMuteBtn = findViewById(R.id.id_btn_mic);
        cameraMuteBtn = findViewById(R.id.id_btn_camera);
        speakerImg = findViewById(R.id.id_img_speaker);
        volumeBar = findViewById(R.id.id_seekBar_volume);
        leaveMeetingBtn = findViewById(R.id.id_btn_leaveMeeting);
        endMeetingCheckbox = findViewById(R.id.id_checkbox_endMeeting);
        projectionBtn = findViewById(R.id.id_btn_projection_start);
        projectionStopBtn = findViewById(R.id.id_btn_projection_stop);
        versionTxt = findViewById(R.id.id_txt_SDKVersion);
        // 设置音频采集开关
        LogUtil.info(TAG, "audio status = " + audioEnabled);
        audioEnabled = false;
        audioSwitch.setChecked(false);
        shareServiceController.enableAudio(this, false);
        audioSwitch.setOnCheckedChangeListener(new CheckBtnListener());
        // 音量改动事件监听
        volumeBar.setOnSeekBarChangeListener(new VolumeListener());
        // 初始化组件状态
        shareServiceController.getRemoteServiceStatus(new Callback<RemoteServiceStatus>() {
            @Override
            public void onSuccess(RemoteServiceStatus remoteServiceStatus) {
                Message msg = new Message();
                msg.what = INIT_COMPONENT_SIGNAL;
                msg.obj = remoteServiceStatus;
                handler.sendMessage(msg);
            }

            @Override
            public void onFailed(int retCode, String desc) {
                sendErrorSignal(retCode);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DemoApp.getInstance().detachMeetingObserver(this);
        shareServiceController.disconnect(new Callback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
            }

            @Override
            public void onFailed(int i, String s) {
            }
        });
    }

    private void setComponentStatus(RemoteServiceStatus remoteServiceStatus) {
        isMicMute = remoteServiceStatus.isMute();
        isCameraMute = remoteServiceStatus.isCameraMute();
        isSpeakerMute = remoteServiceStatus.isSpeakerMute();
        int volume = remoteServiceStatus.getVolume();
        boolean isMeeting = remoteServiceStatus.getCallStatus() == CallStatus.CALLING;
        isChairman = remoteServiceStatus.isChairman();
        boolean isIdeaHub = remoteServiceStatus.isBase();

        micMuteBtn.setText(isMicMute ? "Cancel Mute" : "Mic Mute");

        cameraMuteBtn.setText(isCameraMute ? "Cancel Mute" : "Camera Mute");

        speakerImg.setImageResource(isSpeakerMute ? R.drawable.ic_speaker_mute : R.drawable.ic_speaker_unmute);

        volumeBar.setProgress(volume);

        if (isMeeting) {
            leaveMeetingBtn.setVisibility(View.VISIBLE);
            if (isChairman) {
                endMeetingCheckbox.setChecked(false);
                endMeetingCheckbox.setVisibility(View.VISIBLE);
            } else {
                endMeetingCheckbox.setVisibility(View.GONE);
            }
        } else {
            leaveMeetingBtn.setVisibility(View.GONE);
            endMeetingCheckbox.setVisibility(View.GONE);
        }

        cameraMuteBtn.setEnabled(isIdeaHub);
    }

    /**
     * 禁用mic开关
     *
     * @param view view
     */
    public void micMuteClick(View view) {
        shareServiceController.setRemoteMicMute(!isMicMute, new Callback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Message msg = new Message();
                msg.what = SET_MIC_MUTE_SIGNAL;
                handler.sendMessage(msg);
            }

            @Override
            public void onFailed(int retCode, String desc) {
                sendErrorSignal(retCode);
            }
        });
    }

    /**
     * 禁用摄像头
     *
     * @param view view
     */
    public void cameraMuteClick(View view) {
        shareServiceController.setRemoteCameraMute(!isCameraMute, new Callback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Message msg = new Message();
                msg.what = SET_CAMERA_MUTE_SIGNAL;
                handler.sendMessage(msg);
            }

            @Override
            public void onFailed(int retCode, String desc) {
                sendErrorSignal(retCode);
            }
        });
    }

    /**
     * 扬声器静音开关
     *
     * @param view view
     */
    public void speakerMuteClick(View view) {
        shareServiceController.setRemoteSpeakerMute(!isSpeakerMute, new Callback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Message msg = new Message();
                msg.what = SET_SPEAKER_MUTE_SIGNAL;
                handler.sendMessage(msg);
            }

            @Override
            public void onFailed(int retCode, String desc) {
                sendErrorSignal(retCode);
            }
        });
    }

    private void sendErrorSignal(int retCode) {
        Message msg = new Message();
        msg.what = ERROR_SIGNAL;
        msg.arg1 = retCode;
        handler.sendMessage(msg);
    }

    /**
     * 开始投屏
     *
     * @param view view
     */
    public void projectionClick(View view) {
        shareServiceController.confirmPermissionBeforeSharing(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult: requestCode=" + requestCode + "; grantResults=" + Arrays.toString(grantResults));
        if (requestCode == Constant.AUDIO_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                ShareServiceController serviceController = (ShareServiceController) shareServiceController;
                serviceController.startAudioCapture();
            } else {
                audioEnabled = false;
                audioSwitch.setChecked(false);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 确认权限后开始投屏
        LogUtil.debug(TAG, "Get User Permissions!!!!");
        shareServiceController.startSharing(requestCode, resultCode, data, new Callback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Message msg = new Message();
                msg.what = PROJECTION_SUCCESS_SIGNAL;
                handler.sendMessage(msg);
            }

            @Override
            public void onFailed(int retCode, String s) {
                sendErrorSignal(retCode);
            }
        });

    }

    @Override
    public void updateRemoteServiceStatus(RemoteServiceStatus remoteServiceStatus) {
        LogUtil.debug(TAG, "get remote service status update: " + remoteServiceStatus);
        Message msg = new Message();
        msg.what = INIT_COMPONENT_SIGNAL;
        msg.obj = remoteServiceStatus;
        handler.sendMessage(msg);
    }

    @Override
    public void updateShareStatus(ShareStatus shareStatus) {
        LogUtil.debug(TAG, "get share status update: " + shareStatus);
        if (shareStatus == ShareStatus.DISCONNECT) {
            finish();
        }
        if (shareStatus == ShareStatus.STOPSHARING) {
            Message msg = new Message();
            msg.what = PROJECTION_STOP_SIGNAL;
            handler.sendMessage(msg);
        }
    }

    /**
     * 断开连接
     *
     * @param view view
     */
    public void disconnectClick(View view) {
        shareServiceController.disconnect(new Callback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                finish();
            }

            @Override
            public void onFailed(int retCode, String desc) {
                sendErrorSignal(retCode);
            }
        });
    }

    /**
     * 离开会议
     *
     * @param view view
     */
    public void leaveMeetingClick(View view) {
        shareServiceController.leaveConference(endMeetingCheckbox.isChecked(), new Callback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Message msg = new Message();
                msg.what = LEAVE_MEETING_SIGNAL;
                handler.sendMessage(msg);
            }

            @Override
            public void onFailed(int retCode, String desc) {
                sendErrorSignal(retCode);
            }
        });
    }

    /**
     * 停止投屏
     *
     * @param view view
     */
    public void projectionStopClick(View view) {
        shareServiceController.stopSharing(new Callback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Message msg = new Message();
                msg.what = PROJECTION_STOP_SIGNAL;
                handler.sendMessage(msg);
            }

            @Override
            public void onFailed(int retCode, String desc) {
                sendErrorSignal(retCode);
            }
        });
    }

    /**
     * 获取版本号
     *
     * @param view view
     */
    public void getSdkVersionClick(View view) {
        shareServiceController.getSdkLatestVersion(new Callback<String>() {
            @Override
            public void onSuccess(String s) {
                Message msg = new Message();
                msg.what = SDK_VERSION_SIGNAL;
                msg.obj = s;
                handler.sendMessage(msg);
            }

            @Override
            public void onFailed(int retCode, String s) {
                sendErrorSignal(retCode);
            }
        });
    }

    /**
     * 音量监控
     */
    class VolumeListener implements SeekBar.OnSeekBarChangeListener {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            shareServiceController.setRemoteSpeakerVolume(seekBar.getProgress(), new Callback<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    LogUtil.debug(TAG, "Volume set Success!!!!");
                }

                @Override
                public void onFailed(int retCode, String desc) {
                    sendErrorSignal(retCode);
                }
            });
        }
    }

    /**
     * 音频控制开关
     */
    class CheckBtnListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int ret;
            if (isChecked) {
                LogUtil.info(TAG, "open audio switch...");
                ret = shareServiceController.enableAudio(RemoteActivity.this, true);
                if (ret != 0) {
                    LogUtil.info(TAG, "not support audio capture...ret = " + ret);
                    audioSwitch.setChecked(false);
                    sendErrorSignal(100);
                    return;
                }
                audioEnabled = true;
            } else {
                LogUtil.info(TAG, "close audio switch...");
                ret = shareServiceController.enableAudio(RemoteActivity.this, false);
                if (ret != 0) {
                    LogUtil.info(TAG, "not support audio capture...ret = " + ret);
                    audioSwitch.setChecked(true);
                    sendErrorSignal(100);
                    return;
                }
                audioEnabled = false;
            }
        }
    }
}
